//=============================================================================
// A XueYu Plugins - Title Video
// AXY_TitleVideo.js
// Version: 1.07
// License: MIT(or respect PrimeHover's Creative Commons Attribution 4.0 International License)
//=============================================================================
/*:
 * @plugindesc v1.05 Allows to Change Title Screen Background to Video.
 * @author A XueYu Plugins 老饕
 *
 * @help
 * Introduction
 * This plugin allows to Change Title Screen Background to Video.
 * This plugin base on PrimeHover's PH - Video Title plugin that's version 1.1 post on 4 years ago which 11/12/2015.
 * And his work is licensed under the Creative Commons Attribution 4.0 International License.
 * To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
 *
 * changelog
 * 1.07 2020.12.5
 * add: play bgm only once.(SWDA)
 * 1.06 2020.4.23
 * add: title images fade in.(SWDA)
 * 1.05 2019.11.16
 * add: pause() in setVideoTexture();
 * add: autoPlay = false;setAttribute('controls', '');setAttribute('preload', 'auto'); in setControlOptions();
 * add: playPromise in playVideo();
 * 1.04 2019.11.15
 * add: Continue the video after returning from other scenes;
 * fix: In some cases the problem of the video staying on the first frame;
 * 1.03 2019.11.14
 * add: param: title1Alpha, videoAlpha, title2Alpha. If you want to set the transparent of the video, title1 or title2 ;
 * 1.02 2019.11.13
 * add: click or touch event, pause or play video;
 * add: support system title2 layer, so you can put a title image on the video;
 * 1.01 2019.11.12
 * add: support mobile device;
 * fix: black title screen background when play video but sound is normal play;
 * fix: always play video when leave title screen;
 * modify: use new param format;
 * modify: video name without ext;
 * modify: image name chooser;
 * optimize: memory and performance;
 * 1.00 2019.11.11
 * first release.
 *
 * //=============================================================================
 * End of Help File
 * //=============================================================================
 *
 * @param videoName
 * @text Video Name
 * @desc File name for the video without ext name in movies folder
 * @type text
 *
 * @param imageName
 * @text Image Name
 * @desc File path for the image shown when the video is loading
 * @type file
 * @dir img
 * @require 1
 *
 * @param x
 * @text X
 * @desc The x position of video upper left corner. default:0
 * @type number
 * @default 0
 *
 * @param y
 * @text Y
 * @desc The y position of video upper left corner. default:0
 * @type number
 * @default 0
 *
 * @param width
 * @text Width
 * @desc The video box width. default:816
 * @type number
 * @default 816
 *
 * @param height
 * @text Height
 * @desc The video box height. default:624
 * @type number
 * @default 624
 *
 * @param muted
 * @text Muted
 * @desc Video muted? true/false default:false
 * @type boolean
 * @default false
 *
 * @param loop
 * @text Loop
 * @desc Video loop? true/false default:true
 * @type boolean
 * @default true
 *
 * @param title1Alpha
 * @text Title 1 Alpha
 * @desc The alpha of title 1 that is lower layer. ranges:0-1 default:1
 * @type text
 * @default 1
 *
 * @param videoAlpha
 * @text Video Alpha
 * @desc The alpha of video that is middle layer. ranges:0-1 default:0.5
 * @type text
 * @default 0.5
 *
 * @param title2Alpha
 * @text Title 2 Alpha
 * @desc The alpha of title 2 that is upper layer. ranges:0-1 default:0.5
 * @type text
 * @default 0.5
 *
 * @param TitleImage1
 * @desc 叠加图层1文件名
 * @default Title1
 
 * @param TitleImage2
 * @desc 叠加图层2文件名
 * @default Title2
 * 
 * @param wait1
 * @desc 标题背景到叠加图层1开始显示的等待时间（s）
 * @default 0.1
 * 
 * @param wait2
 * @desc 叠加图层1到叠加图层2开始显示的等待时间（s）
 * @default 0.1
 * 
 * @param wait3
 * @desc 叠加图层2到显示命令窗口开始显示的等待时间（s）
 * @default 0.1
 * 
 * @param fade1
 * @desc 叠加图层1的淡入时间（s）
 * @default 0.2
 * 
 * @param fade2
 * @desc 叠加图层2的淡入时间（s）
 * @default 0.2
 *
 */

// Imported
var Imported = Imported || {};
Imported.AXY_TitleVideo = true;

// Parameter Variables
var AXY = AXY || {};
AXY.TitleVideo = AXY.TitleVideo || {};
AXY.TitleVideo.Parameters = PluginManager.parameters('AXY_TitleVideo');

//
AXY.TitleVideo.Param = AXY.TitleVideo.Param || {};
AXY.TitleVideo.Alias = AXY.TitleVideo.Alias || {};
AXY.TitleVideo.Variables = AXY.TitleVideo.Variables || {};


AXY.TitleVideo.Parameters.titleImage1  = String(AXY.TitleVideo.Parameters['Title1']   || 'Title1');
AXY.TitleVideo.Parameters.titleImage2  = String(AXY.TitleVideo.Parameters['Title2']   || 'Title2');

AXY.TitleVideo.Parameters.wait1  = String(AXY.TitleVideo.Parameters['wait1']   || '0.1');
AXY.TitleVideo.Parameters.wait2  = String(AXY.TitleVideo.Parameters['wait2']   || '0.1');
AXY.TitleVideo.Parameters.wait3  = String(AXY.TitleVideo.Parameters['wait3']   || '0.1');

AXY.TitleVideo.Parameters.fade1  = String(AXY.TitleVideo.Parameters['fade1']   || '0.2');
AXY.TitleVideo.Parameters.fade2  = String(AXY.TitleVideo.Parameters['fade2']   || '0.2');

AXY.TitleVideo.Parameters.count1 = 60 * AXY.TitleVideo.Parameters.wait1;	//标题背景到titleImage1
AXY.TitleVideo.Parameters.count2 = 60 * AXY.TitleVideo.Parameters.wait2;	//titleImage1到titleImage2
AXY.TitleVideo.Parameters.count3 = 60 * AXY.TitleVideo.Parameters.wait3;	//titleImage2到命令窗口



//=============================================================================
// Utils
//=============================================================================
// Create a utility function to parse complex parameters.
//=============================================================================
Utils.recursiveParse = function (param) {
	try {
		if (typeof JSON.parse(param) == 'object') {
			return JSON.parse(
				param,
				function (key, value) {
					try {
						return this.recursiveParse(value);
					} catch (e) {
						return value;
					}
				}.bind(this)
			);
		} else {
			return JSON.parse(
				param,
				function (key, value) {
					return value;
				}.bind(this)
			);
		}
	} catch (e) {
		return param;
	}
};

//=============================================================================
// Parameters
//=============================================================================
// Read and parse parameters into a locally scoped Parameters object.
//=============================================================================
Object.keys(AXY.TitleVideo.Parameters).forEach(function (key) {
	return (AXY.TitleVideo.Param[key] = Utils.recursiveParse(
		AXY.TitleVideo.Parameters[key]
	));
});

//Variables
AXY.TitleVideo.Variables.playStatus = false;
AXY.TitleVideo.Variables.lastRunTime = Date.now();

// Main
(function () {
	// Video Title Class
	// var PH_VideoTitle = null;
	var AXY_TitleVideo = null;

	TitleVideo = function () {
		this.videoName =
			'movies/' +
			AXY.TitleVideo.Param.videoName +
			Game_Interpreter.prototype.videoFileExt(AXY.TitleVideo.Param.videoName);
		//this.videoName ='movies/' + AXY.TitleVideo.Param.videoName + '.webm';
		this.imageName = 'img/' + AXY.TitleVideo.Param.imageName + '.png';
		if (Decrypter.hasEncryptedImages) {
			this.imageName = Decrypter.extToEncryptExt(this.imageName);
		}

		// Starts video and creates the texture
		this.setVideoTexture();

	};
	TitleVideo.prototype.constructor = TitleVideo;

	TitleVideo.prototype.setVideoTexture = function () {
		//this._texture = PIXI.VideoTexture.textureFromVideo(this._video);
		//this._texture = PIXI.Texture.fromVideo(this._video);
		//this._texture = PIXI.Texture.fromVideo('movies/' + this.name + '.webm');
		//this._texture = PIXI.Texture.from(this._video);
		this._texture = PIXI.Texture.from(this.videoName);
		this._videoSource = this._texture.baseTexture.source;
		this.setControlOptions();
		this._videoSource.pause();
		//this._texture.baseTexture.source.pause();

		this._spriteVideo = new PIXI.Sprite(this._texture);
		this._spriteVideo.width = AXY.TitleVideo.Param.width;
		this._spriteVideo.height = AXY.TitleVideo.Param.height;
		this._spriteVideo.x = AXY.TitleVideo.Param.x;
		this._spriteVideo.y = AXY.TitleVideo.Param.y;
	};

	TitleVideo.prototype.setControlOptions = function () {
		if (AXY.TitleVideo.Param.loop == true) {
			this._videoSource.loop = true;
		} else {
			this._videoSource.loop = false;
		}

		if (AXY.TitleVideo.Param.muted == true) {
			this._videoSource.muted = true;
		} else {
			this._videoSource.muted = false;
		}

		if (this.imageName.trim() != '') {
			this._videoSource.poster = this.imageName;
		}

		this._videoSource.autoPlay = false;
		this._videoSource.setAttribute('controls', '');
		this._videoSource.setAttribute('preload', 'auto');
	};

	TitleVideo.prototype.pauseVideo = function () {
		this._videoSource.pause();
	};

	TitleVideo.prototype.playVideo = function () {
		let playPromise = this._videoSource.play();
		if (playPromise !== undefined) {
			playPromise.then(() => {
				this._videoSource.play();
			}).catch((e) => {
				console.log(e);
				this._videoSource.load();
				this.playVideo();
			})
		}
	}

	TitleVideo.prototype.removeVideo = function () {
		this._videoSource.pause();
		this._videoSource.src = null;
		this._videoSource.removeAttribute('src');
		this._videoSource.load();
	};

	TitleVideo.prototype.update = function () {
		this._texture.update();
		/*
		if (Input.isTriggered('ok') || TouchInput.isTriggered()) {
			if (this._videoSource.paused) {
				this.playVideo();
			} else {
				this.pauseVideo();
			}
		}*/
	};

	// Overwritten Scene_Title methods
	Scene_Title.prototype.create = function () {
		// Prevent the video to be duplicated

		if (AXY_TitleVideo === null) {
			AXY_TitleVideo = new TitleVideo();
			this.titleVideo = AXY_TitleVideo;
		} else {
			this.titleVideo = AXY_TitleVideo;
			this.titleVideo.playVideo();
		}

		this._backSprite1 = new Sprite(ImageManager.loadTitle1($dataSystem.title1Name));
		this._backSprite1.alpha = AXY.TitleVideo.Param.title1Alpha;
		this.addChild(this._backSprite1);

		this.titleVideo._spriteVideo.alpha = AXY.TitleVideo.Param.videoAlpha;
		this.addChild(this.titleVideo._spriteVideo);

		this._backSprite2 = new Sprite(ImageManager.loadTitle2($dataSystem.title2Name));
		this._backSprite2.alpha = AXY.TitleVideo.Param.title2Alpha;
		this.addChild(this._backSprite2);
		
		this.createBackground1();
		this.createForeground();
		this.createWindowLayer();
		this.createCommandWindow();
		this._frameCount = 0;
	};
	//SWDA：
	Scene_Title.prototype.commandNewGame = function() {
		DataManager.setupNewGame();
		this._commandWindow.close();
		this.fadeOutAll();
		SceneManager.goto(Scene_Map);
		SceneManager._isTitleOptions = false;
	};
	
	//SWDA：覆盖图层
	Scene_Title.prototype.createBackground1 = function() {
		/*
		Graphics.BLEND_NORMAL   = 0;
		Graphics.BLEND_ADD      = 1;
		Graphics.BLEND_MULTIPLY = 2;
		Graphics.BLEND_SCREEN   = 3;
		*/
		this._newbackSprite1 = new Sprite(ImageManager.loadTitle1(AXY.TitleVideo.Parameters.titleImage1));
		this._newbackSprite1.opacity = 0;
		this._newbackSprite1.blendMode = 2;
		this._newbackSprite1a = new Sprite(ImageManager.loadTitle1(AXY.TitleVideo.Parameters.titleImage1 + 'a'));
		this._newbackSprite1a.opacity = 0;
		this.addChild(this._newbackSprite1);
		this.addChild(this._newbackSprite1a);

		this._newbackSprite2 = new Sprite(ImageManager.loadTitle1(AXY.TitleVideo.Parameters.titleImage2));
		this._newbackSprite2.opacity = 0;
		this._newbackSprite2.blendMode = 1;
		this._newbackSprite2.anchor.x = 0.5;
		this._newbackSprite2.anchor.y = 0.6125;
		this._newbackSprite2.scale.x = 0;
		this._newbackSprite2.scale.y = 0;
		this._newbackSprite2.x = Graphics.boxWidth/2;
		this._newbackSprite2.y = this._newbackSprite2.anchor.y * Graphics.boxHeight;
		this._newbackSprite2a = new Sprite(ImageManager.loadTitle1(AXY.TitleVideo.Parameters.titleImage2 + 'a'));
		this._newbackSprite2a.opacity = 0;
		this._newbackSprite2a.anchor.x = 0.5;
		this._newbackSprite2a.scale.x = 0;
		this._newbackSprite2a.x = Graphics.boxWidth/2;

		this.addChild(this._newbackSprite2);
		this.addChild(this._newbackSprite2a);
	};
	
	Scene_Title.prototype.start = function () {
		Scene_Base.prototype.start.call(this);
		SceneManager.clearStack();
		SceneManager._isTitleOptions = true;
		//if (AXY.TitleVideo.Param.muted == true) {
			this.playTitleMusic();
		//}
		if(SceneManager._previousClass != Scene_Load && SceneManager._previousClass != Scene_Options){
			this.startFadeIn(60, false);
		}
	};

	Scene_Title.prototype.terminate = function () {
		Scene_Base.prototype.terminate.call(this);
		this.titleVideo.pauseVideo();
		SceneManager.snapForBackground();
	};
	// 让BGM只播放一遍，不循环
	Scene_Title.prototype.playTitleMusic = function() {
		AudioManager.playTitleBgm($dataSystem.titleBgm);
		AudioManager.stopBgs();
		AudioManager.stopMe();
	};
	// 让BGM只播放一遍，不循环
	AudioManager.playTitleBgm = function(bgm, pos) {
		if (this.isCurrentBgm(bgm)) {
			this.updateBgmParameters(bgm);
		} else {
			this.stopBgm();
			if (bgm.name) { 
				if(Decrypter.hasEncryptedAudio && this.shouldUseHtml5Audio()){
					this.playEncryptedBgm(bgm, pos);
				}
				else {
					this._bgmBuffer = this.createBuffer('bgm', bgm.name);
					this.updateBgmParameters(bgm);
					if (!this._meBuffer) {
						this._bgmBuffer.play(false, pos || 0);
					}
				}
			}
		}
		this.updateCurrentBgm(bgm, pos);
	};
	

	//AXY.TitleVideo.Alias.Scene_Title_update = Scene_Title.prototype.update;
	Scene_Title.prototype.update = function () {
		Scene_Base.prototype.update.call(this);
		//AXY.TitleVideo.Alias.Scene_Title_update.call(this);
		this.titleVideo.update();
		if(SceneManager._previousClass != Scene_Load && SceneManager._previousClass != Scene_Options){
			//重定义刷新：图层淡入完成后打开窗口
			if (this._frameCount < AXY.TitleVideo.Parameters.count1) {
				this._frameCount += 1;
			} else if (this._newbackSprite1.opacity < 255) {
				this._newbackSprite1.opacity += 255 / (AXY.TitleVideo.Parameters.fade1 * 60);
				this._newbackSprite1a.opacity += 255 / (AXY.TitleVideo.Parameters.fade1 * 60);
			} else if(this._frameCount < AXY.TitleVideo.Parameters.count1 + AXY.TitleVideo.Parameters.count2) {
				this._frameCount += 1;
			} else if (this._newbackSprite2.opacity < 255) {
				this._newbackSprite2.opacity += 255 / (AXY.TitleVideo.Parameters.fade2 * 60);
				this._newbackSprite2.scale.x += 1 / (AXY.TitleVideo.Parameters.fade2 * 60);
				this._newbackSprite2.scale.y += 1 / (AXY.TitleVideo.Parameters.fade2 * 60);
				if (this._newbackSprite2.opacity > 255/4*3) {
					this._newbackSprite2a.opacity += 255 / (AXY.TitleVideo.Parameters.fade2 * 60 / 4);
					this._newbackSprite2a.scale.x += 1 / (AXY.TitleVideo.Parameters.fade2 * 60 / 4);
					if(this._newbackSprite2a.scale.x >= 0.999)
						this._newbackSprite2a.scale.x = 1;
				}
			} else if(this._frameCount < AXY.TitleVideo.Parameters.count1 + AXY.TitleVideo.Parameters.count2 + AXY.TitleVideo.Parameters.count3) {
				this._frameCount += 1;
			} else if(this._frameCount == AXY.TitleVideo.Parameters.count1 + AXY.TitleVideo.Parameters.count2 + AXY.TitleVideo.Parameters.count3) {
				if (!this.isBusy()) {
					this._commandWindow.open();
				}
			}
		}else{
			this._newbackSprite1.opacity = 255;
			this._newbackSprite2.opacity = 255;
			this._newbackSprite1a.opacity = 255;
			this._newbackSprite2a.opacity = 255;
			this._newbackSprite2.scale.x = 1;
			this._newbackSprite2.scale.y = 1;
			this._newbackSprite2a.scale.x = 1;
			this._commandWindow.open();
			
		}
	};
	
	
	// SWDA:命令窗口位置
	Window_TitleCommand.prototype.updatePlacement = function() {
		this.x = (Graphics.boxWidth - this.width) / 2;
		this.y = Graphics.boxHeight - this.height - 24;
	};
	
	Scene_Title.prototype.stop = function() {
		Scene_Base.prototype.stop.call(this);
		/*
		if (SceneManager.isNextScene(Scene_Load)||SceneManager.isNextScene(Scene_Options)) {
			this.startFadeOut(this.fadeSpeed());
		} 
		*/
	};

})();